import api from './api.js';

export default {
  template: `
    <div>
      <el-input placeholder="搜索菜品" v-model="search" @input="searchDishes" clearable></el-input>
      <el-table :data="filteredMenuData" style="width: 100%">
        <el-table-column prop="name" label="菜名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="description" label="简介" header-align="center" align="center"></el-table-column>
        <el-table-column prop="image" label="图片" header-align="center" align="center">
          <template #default="scope">
            <img :src="scope.row.image" alt="图片" style="width: 50px; height: 50px;"/>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" header-align="center" align="center"></el-table-column>
        <el-table-column label="购买" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" @click="addToCart(scope.$index, scope.row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  `,
  props: ['userInfo', 'isLoggedIn'],
  data() {
    return {
      search: '',
      orderId: 0,
      menuData: [],
    };
  },
  async created() {
    const resp = await api.getDishes();
    this.menuData = resp.data.data;
    if (this.isLoggedIn) {
      this.updateOrderId();
    }
  },
  methods: {
    async addToCart(index, row) {
      if (!this.isLoggedIn) {
        this.$message.error('请先登录');
        return;
      }
      const orderId = this.orderId;
      try {
        await api.addOrderDish(orderId, row.dishId);
        this.$message.success('菜品已成功添加到购物车');
      } catch (error) {
        this.$message.error('添加菜品到购物车失败');
      }
    },
    async updateOrderId() {
      try {
        const response = await api.getOrdersByStatus(this.userInfo.id, 1);
        if (response.data.data) {
          this.orderId = response.data.data[0].orderId;
        } else {
          const createOrderResponse = await api.createOrder(this.userInfo.id);
          this.orderId = createOrderResponse.data.data.orderId;
        }
      } catch (error) {
        console.error(error);
      }
    },
    searchDishes() {
      if (this.search) {
        this.filteredMenuData = this.menuData.filter(dish =>
          dish.name.includes(this.search) || dish.description.includes(this.search)
        );
      } else {
        this.filteredMenuData = this.menuData;
      }
    },
  },
  computed: {
    filteredMenuData() {
      if (this.search) {
        return this.menuData.filter(dish =>
          dish.name.includes(this.search) || dish.description.includes(this.search)
        );
      }
      return this.menuData;
    },
  },
  watch: {
    isLoggedIn() {
      this.updateOrderId();
    }
  }
};
